/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sbmart.smartserver.job;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sbmart.object.Header;
import sbmart.object.MstConnection;
import sbmart.smartserver.cache.DataSourcePool;
import sbmart.smartserver.task.ClientQueryTask;

/**
 *
 * @author albert
 *
 */
public class ClientQueryJob {

    private ExecutorService exec;
    private Hashtable<Integer, List<Header>> headerPool = new Hashtable<Integer, List<Header>>();
    public static final Logger LOG = LoggerFactory.getLogger(ClientQueryJob.class);

     public void init() {

        HashMap<Integer, MstConnection> branchs = DataSourcePool.instance().getMstConnection();
        List<Header> headers = new ArrayList<Header>();

        for (Iterator<MstConnection> it = branchs.values().iterator(); it.hasNext();) {
            MstConnection branch = it.next();
            Header header = new Header();
            header.setBranchId(branch.getBranchId());
            header.setIpaddress(branch.getIpaddress());
            header.setBranchName(branch.getBranchName());
            header.setNickname(branch.getNickname());
            header.setUsername(branch.getUsername());
            header.setPassword(branch.getPassword());
            headers.add(header);
        }
        headerPool.put(Integer.valueOf(0), headers);
    }

    public void runTasks() {
        LOG.debug("[RUN]");
        try {
            init();
            if (exec == null || exec.isTerminated()) {
                LOG.info("");
                LOG.info("");
                LOG.info("<TASK RUN> " + getClass().getSimpleName() + "  " + Calendar.getInstance().getTime().toString());
                executeTask();
            }
        } catch (Exception ex) {
            LOG.error("[ERROR] runTask", ex);
        } finally {
        }
    }

    private void executeTask() {
        exec = Executors.newCachedThreadPool();
        for (int i = 0; i < headerPool.size(); i++) {
            exec.execute(new ClientQueryTask(headerPool.get(i), exec));
        }
        exec.shutdown();
        try {
            if (!exec.awaitTermination(60, TimeUnit.MINUTES)) {
                exec.shutdownNow();
            }
        } catch (final InterruptedException ex) {
            exec.shutdownNow();
            Thread.currentThread().interrupt();

        }
    }
}
